<template>
  <div>
    <a-card title="销售开单">
      <a-spin :spinning="loading">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-row>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="number" label="销售编号">
                <a-input v-model="form.number" />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="warehouse" label="仓库">
                <a-select v-model="form.warehouse" style="width: 100%">
                  <a-select-option
                    v-for="item in warehouseItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="client" label="客户">
                <a-select
                  showSearch
                  v-model="form.client"
                  style="width: 100%"
                  :filterOption="filterOption"
                >
                  <a-select-option
                    v-for="item in clientsItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="handler" label="经手人">
                <a-select v-model="form.handler" style="width: 100%">
                  <a-select-option
                    v-for="item in handlerItems"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="handle_time" label="处理日期">
                <!-- <a-date-picker v-model="form.handle_time" valueFormat="YYYY-MM-DD" style="width: 100%" /> -->
                <a-date-picker
                  v-model="form.handle_time"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="6" style="width: 320px">
              <a-form-model-item prop="remark" label="备注">
                <a-input v-model="form.remark" allowClear />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>

        <a-divider orientation="left">产品信息</a-divider>

        <div>
          <a-row gutter="16">
            <a-space>
              <a-button
                type="primary"
                @click="openMaterialModal"
                style="float: right"
                >添加产品</a-button
              >
            </a-space>
          </a-row>
          <div style="margin-top: 16px">
            <a-table
              bordered
              rowKey="id"
              size="middle"
              :columns="columns"
              :data-source="goodsData"
              :pagination="false"
              v-if="!canshu.is_dagong_table"
            >
              <div slot="guige" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.guige"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="jianshu" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.jianshu"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input-number>
              </div>
              <div slot="cldz" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.cldz"
                  size="small"
                  @change="cal_total_zl(item)"
                ></a-input>
              </div>
              <div slot="cldj" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.cldj"
                  :min="0"
                  size="small"
                ></a-input-number>
              </div>
              <div slot="dts" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.dts"
                  size="small"
                ></a-input>
              </div>
              <div slot="tgdj" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.tgdj"
                  :min="0"
                  size="small"
                ></a-input-number>
              </div>
              <div slot="tgAmount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="jgry" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-select
                  v-model="item.jgry"
                  mode="multiple"
                  allowClear
                  style="width: 100%"
                  :filterOption="filterOption"
                  @change="jgryChange(item)"
                  :key="index"
                  v-else
                >
                  <a-select-option
                    v-for="item in jg_handlerItems"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
              <div slot="jgfl" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-select
                  v-model="item.jgfl"
                  allowClear
                  style="width: 100%"
                  v-else
                >
                  <a-select-option
                    v-for="item in jgfltems"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
              <div slot="totalAmount" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="beizhu" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.beizhu"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="action" slot-scope="value, item, index">
                <a-button-group v-if="!item.isTotal" size="small">
                  <a-button type="danger" @click="removeMaterial(item)"
                    >移除</a-button
                  >
                </a-button-group>
              </div>
            </a-table>
            <a-table
              bordered
              rowKey="id"
              size="middle"
              :columns="columns_dagong_data"
              :data-source="goodsData"
              :pagination="false"
              v-if="canshu.is_dagong_table"
            >
              <div slot="cailiao_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.cailiao_dg"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="sales_quantity" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input-number
                  v-else
                  v-model="item.sales_quantity"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input-number>
              </div>
              <div slot="chang_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.chang_dg"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="kuan_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.kuan_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="hou_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.hou_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="zhong_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
              </div>
              <div slot="mianji_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
              </div>
              <div slot="yldj_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.yldj_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="clAmount_dg" slot-scope="value, item, index">
                <div>{{ value ? 1 : 0 }}</div>
              </div>
              <div slot="jgcd_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.jgcd_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="jgdj_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.jgdj_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="jgAmount_dg" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="jgry" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-select
                  v-model="item.jgry"
                  mode="multiple"
                  allowClear
                  style="width: 100%"
                  v-else
                >
                  <a-select-option
                    v-for="item in jg_handlerItems"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
              <div slot="jgfl" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-select
                  v-model="item.jgfl"
                  allowClear
                  style="width: 100%"
                  v-else
                >
                  <a-select-option
                    v-for="item in jgfltems"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}
                  </a-select-option>
                </a-select>
              </div>
              <div slot="kongshu_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.kongshu_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="kongdj_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.kongdj_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="kongAmount_dg" slot-scope="value, item, index">
                <div>{{ value }}</div>
              </div>
              <div slot="lingjiansl_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.lingjiansl_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="lingjianDj_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.lingjianDj_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="ljtotalAmount_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
              </div>
              <div slot="flzhong_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.flzhong_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="feiliaodj_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.feiliaodj_dg"
                  :min="0"
                  size="small"
                ></a-input>
              </div>
              <div slot="feiliaoAmount_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
              </div>
              <div slot="shifuAmount_dg" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
              </div>
              <div slot="beizhu" slot-scope="value, item, index">
                <div v-if="item.isTotal">{{ value }}</div>
                <a-input
                  v-else
                  v-model="item.beizhu"
                  :min="0"
                  size="small"
                  placeholder=""
                  bordered="{false}"
                ></a-input>
              </div>
              <div slot="action" slot-scope="value, item, index">
                <a-button-group v-if="!item.isTotal" size="small">
                  <a-button type="danger" @click="removeMaterial(item)"
                    >移除</a-button
                  >
                </a-button-group>
              </div>
            </a-table>
          </div>
        </div>
        <a-divider orientation="left">账单信息</a-divider>
        <div>
          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                prop="discount"
                label="整单折扣"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input v-model="form.discount" style="width: 100%" />
              </a-form-model-item>
            </a-col>

            <a-col :span="4">
              <a-form-model-item
                prop="other_amount"
                label="其他费用"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input v-model="form.other_amount" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="总计金额(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="totalAmount"
                  :disabled="true"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="总计金额(大写)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="convertCurrency(totalAmount)"
                  :disabled="true"
                  style="width: 100%; color: black"
                />
              </a-form-model-item>
            </a-col>
          </a-row>

          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                label="结算账户"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-select v-model="form.account" style="width: 100%">
                  <a-select-option
                    v-for="Account in accountsItems"
                    :key="Account.id"
                    :value="Account.id"
                  >
                    {{ Account.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="实收金额(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  v-model="sales_account_item.collection_amount"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="本单欠款(元)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="amountOwed"
                  :disabled="true"
                  style="width: 100%"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="4">
              <a-form-model-item
                label="欠款金额(大写)"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-input
                  :value="convertCurrency(amountOwed)"
                  :disabled="true"
                  style="width: 100%; color: black"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row gutter="16">
            <a-col :span="4">
              <a-form-model-item
                label="是否已付款"
                :label-col="{ span: 24 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-switch
                  v-model="form.qualification_status"
                  checkedChildren="已付款"
                  unCheckedChildren="未付款"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-spin>

      <div style="margin-top: 10px">
        <a-popconfirm title="确定开单吗?" @confirm="create">
          <a-button type="primary" :loading="loading">开单</a-button>
        </a-popconfirm>
      </div>
    </a-card>
    <!-- v-model="materialsSelectModalVisible" -->
    <materials-select-modal
      v-model="materialsSelectModalVisible"
      :warehouse="form.warehouse"
      @select="onSelectMaterial"
    ></materials-select-modal>
  </div>
</template>

<script>
import moment from "moment";
import _ from "lodash";
import NP from "number-precision";
import { Create, Update, Destroy, List } from "@/api/common";
import { getSaleOrderNumber } from "@/api/data";
import { saleOrderCreate } from "@/api/sale";
import { convertCurrency, datetimeToString } from "@/utils/functions";
import {
  userOption,
  clientsOption,
  warehousesOption,
  inventoriesOption,
  accountsOption,
} from "@/api/option";
import {
  canshu,
  xssl,
  columns,
  columns_dagong,
  rules,
  columnsAccount,
  calzhong_dg,
  calmianji_dg,
  calclAmount,
  caljgAmount_dg,
  callingjianDj_dg,
  calljtotalAmount_dg,
  calshifuAmount_dg,
} from "@/views/sale/saleCreate/js/data";
export default {
  components: {
    MaterialsSelectModal: () =>
      import("@/components/MaterialSelectModal/index"),
  },
  data() {
    return {
      description: "新增",
      warehouseItems: [],
      handlerItems: [],
      jg_handlerItems: [],
      jgfltems: [],
      clientsItems: [],
      accountsItems: [],
      materialsSelectModalVisible: false,
      loading: false,
      model: {},
      form: {
        warehouse: "原材料仓库",
        tableType: false,
        unitType: false,
      },
      rules,
      columns,
      canshu,
      columns_dagong,
      columns_dagong_data: [],
      materialItems: [],
      columnsAccount,
      sales_account_items: [],
      sales_account_item: {},
      is_readSalePrice: false,
      is_jgry_only: true,
      final_jgry: [], //最新一次加工人员
    };
  },
  computed: {
    totalAmount() {
      let totalAmount = 0;
      for (let item of this.materialItems) {
        // let amount = NP.times(item.sales_quantity, item.sales_price);
        if (canshu.is_dagong_table) {
          let total_shifuAmount_dg = calshifuAmount_dg(
            item.chang_dg,
            item.kuan_dg,
            item.hou_dg,
            item.yldj_dg,
            item.jgcd_dg,
            item.jgdj_dg,
            item.kongshu_dg,
            item.kongdj_dg,
            item.lingjiansl_dg,
            item.flzhong_dg,
            item.feiliaodj_dg
          );
          totalAmount = NP.plus(totalAmount, total_shifuAmount_dg);
        } else {
          let amount = NP.plus(
            NP.times(item.clsl, item.cldj),
            NP.times(item.jgsl, item.jgdj)
          );
          totalAmount = NP.plus(totalAmount, amount);
        }
      }

      totalAmount = NP.times(totalAmount, this.form.discount || 100, 0.01);
      totalAmount = NP.plus(totalAmount, this.form.other_amount || 0);
      return NP.round(totalAmount, 2);
    },
    amountOwed() {
      return NP.minus(
        this.totalAmount,
        this.sales_account_item.collection_amount || 0
      );
    },
    goodsData() {
      // 统计合计
      let totalclAmount = 0,
        //普通表格部分
        clAmount = 0,
        jgAmount = 0,
        totaljgAmount = 0,
        totalAmount = 0,
        //大工表格部分
        zhong_dg = 0,
        mianji_dg = 0,
        clAmount_dg = 0,
        jgAmount_dg = 0,
        kongAmount_dg = 0,
        lingjianDj_dg = 0,
        ljtotalAmount_dg = 0,
        feiliaoAmount_dg = 0,
        shifuAmount_dg = 0,
        total_zhong_dg = 0,
        total_mianji_dg = 0,
        total_clAmount_dg = 0,
        total_jgAmount_dg = 0,
        total_kongAmount_dg = 0,
        total_lingjianDj_dg = 0,
        total_ljtotalAmount_dg = 0,
        total_feiliaoAmount_dg = 0,
        total_shifuAmount_dg = 0;

      // for (let item of this.materialItems) {
      //   totalQuantity = NP.plus(totalQuantity, item.sales_quantity);
      //   let amount = NP.times(item.sales_quantity, item.sales_price);
      //   totalAmount = NP.plus(totalAmount, amount);
      // }
      for (let item of this.materialItems) {
        // for (let item of this.materialItems_mid) {
        //普通部分
        totalclAmount = NP.times(item.clsl, item.cldj);
        totaljgAmount = NP.times(item.jgsl, item.jgdj);
        clAmount = NP.plus(clAmount, totalclAmount);
        jgAmount = NP.plus(jgAmount, totaljgAmount);
        totalAmount = NP.plus(totalAmount, totalclAmount, totaljgAmount);

        //大工部分
        total_zhong_dg = calzhong_dg(item.chang_dg, item.kuan_dg, item.hou_dg);
        total_mianji_dg = calmianji_dg(item.chang_dg, item.kuan_dg);
        total_clAmount_dg = calclAmount(
          item.chang_dg,
          item.kuan_dg,
          item.hou_dg,
          item.yldj_dg
        );
        total_jgAmount_dg = caljgAmount_dg(item.jgcd_dg, item.jgdj_dg);
        total_kongAmount_dg = caljgAmount_dg(item.kongshu_dg, item.kongdj_dg);
        total_lingjianDj_dg = callingjianDj_dg(
          item.chang_dg,
          item.kuan_dg,
          item.hou_dg,
          item.yldj_dg,
          item.jgcd_dg,
          item.jgdj_dg,
          item.kongshu_dg,
          item.kongdj_dg
        );
        total_ljtotalAmount_dg = calljtotalAmount_dg(
          item.chang_dg,
          item.kuan_dg,
          item.hou_dg,
          item.yldj_dg,
          item.jgcd_dg,
          item.jgdj_dg,
          item.kongshu_dg,
          item.kongdj_dg,
          item.lingjiansl_dg
        );
        total_feiliaoAmount_dg = caljgAmount_dg(
          item.flzhong_dg,
          item.feiliaodj_dg
        );
        total_shifuAmount_dg = calshifuAmount_dg(
          item.chang_dg,
          item.kuan_dg,
          item.hou_dg,
          item.yldj_dg,
          item.jgcd_dg,
          item.jgdj_dg,
          item.kongshu_dg,
          item.kongdj_dg,
          item.lingjiansl_dg,
          item.flzhong_dg,
          item.feiliaodj_dg
        );
        zhong_dg = NP.round(NP.plus(zhong_dg, total_zhong_dg), 2);
        mianji_dg = NP.round(NP.plus(mianji_dg, total_mianji_dg), 2);
        clAmount_dg = NP.round(NP.plus(clAmount_dg, total_clAmount_dg), 2);
        jgAmount_dg = NP.round(NP.plus(jgAmount_dg, total_jgAmount_dg), 2);
        kongAmount_dg = NP.round(
          NP.plus(kongAmount_dg, total_kongAmount_dg),
          2
        );
        // lingjianDj_dg = NP.round(NP.plus(lingjianDj_dg,total_lingjianDj_dg), 2)
        ljtotalAmount_dg = NP.round(
          NP.plus(ljtotalAmount_dg, total_ljtotalAmount_dg),
          2
        );
        feiliaoAmount_dg = NP.round(
          NP.plus(feiliaoAmount_dg, total_feiliaoAmount_dg),
          2
        );
        shifuAmount_dg = NP.round(
          NP.plus(shifuAmount_dg, total_shifuAmount_dg),
          2
        );
      }
      if (canshu.is_dagong_table) {
        totalAmount = shifuAmount_dg;
      }
      return [
        ...this.materialItems,
        // ...this.materialItems_mid,
        {
          id: "-1",
          isTotal: true,
          name: "",
          // sales_quantity: totalQuantity,
          // totalAmount: `${totalAmount} * ${this.form.discount}% = ${NP.times(
          //   totalAmount,
          //   this.form.discount || 0,
          //   0.01
          // )}`,
          clAmount,
          jgAmount,
          totalAmount,
          zhong_dg,
          mianji_dg,
          clAmount_dg,
          jgAmount_dg,
          kongAmount_dg,
          lingjianDj_dg,
          ljtotalAmount_dg,
          feiliaoAmount_dg,
          shifuAmount_dg,
        },
      ];
    },
    accountsData() {
      // 统计合计
      let totalAmount = 0;
      for (let item of this.sales_account_items) {
        totalAmount = NP.plus(totalAmount, item.collection_amount);
      }
      return [
        ...this.sales_account_items,
        {
          id: "-1",
          isTotal: true,
          collection_amount: totalAmount,
        },
      ];
    },
  },
  methods: {
    get_dict() {
      List({}, `dicts`).then((data) => {
        let res = data.results;
        this.jgfltems = res.filter((i) => i.code == "jgfltems")[0].dict_items;
      });
    },
    tableTypeChange() {
      if (this.form.tableType) {
        this.canshu.is_dagong_table = true;
      } else {
        this.canshu.is_dagong_table = false;
      }
    },
    unitTypeChange() {
      // const arr=JSON.stringify(columns_dagong)
      // this.columns_dagong_data=JSON.parse(arr)
      this.columns_dagong_data = _.cloneDeep(columns_dagong);
      if (this.form.unitType) {
        this.canshu.yongliaojl = false;
        this.columns_dagong_data[5].children.splice(4, 1); //根据用料计量默认为重量删除面积
        this.columns_dagong_data[5].title = "用料（长宽厚：mm，面积：dm²）";
      } else {
        this.canshu.yongliaojl = true;
        this.columns_dagong_data[5].children.splice(5, 1); //根据用料计量默认为重量删除面积
        this.columns_dagong_data[5].title = "用料（长宽厚：mm，重：kg）";
      }
    },
    // 将输入的内容与显示的内容进行匹配
    filterOption(value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0;
    },
    convertCurrency(money) {
      return convertCurrency(money);
    },
    initData() {
      this.get_dict();
      // const arr=JSON.stringify(columns_dagong)
      // this.columns_dagong_data=JSON.parse(arr)
      this.columns_dagong_data = _.cloneDeep(columns_dagong);
      this.columns_dagong_data[5].children.splice(5, 1); //根据用料计量默认为重量删除面积
      this.columns_dagong_data[5].title = "用料（长宽厚：mm，重：kg）";
      this.resetForm();
      warehousesOption({ page_size: 999999, is_active: true }).then((data) => {
        this.warehouseItems = data.results;
        this.form.warehouse = this.warehouseItems[0].id;
      });
      userOption({ page_size: 999999, is_active: true }).then((data) => {
        this.handlerItems = data.results.filter((i) => i.is_manager == true);
        this.jg_handlerItems = data.results.filter(
          (i) => i.is_employee == true
        );
      });
      clientsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.clientsItems = data.results;
      });
      accountsOption({ page_size: 999999, is_active: true }).then((data) => {
        this.accountsItems = data.results;
      });
      this.form.handle_time = datetimeToString(new Date());
    },
    handelAddAcount() {
      this.sales_account_items.push({
        id: this.sales_account_items.length + 1,
        account: "",
        collection_amount: 0,
      });
    },
    removeAccount(item) {
      this.sales_account_items = this.$functions.removeItem(
        this.sales_account_items,
        item
      );
    },
    changeAccount(value, item, idx) {
      let count = this.sales_account_items.filter((_item) => {
        return _item.account == value;
      });
      if (count.length > 1) {
        this.$message.warn("已添加过改结算账户!");
        this.sales_account_items[idx].account = "";
      }
    },
    openMaterialModal() {
      if (!this.form.warehouse) {
        this.$message.warn("请先选择仓库！");
        return false;
      }
      this.materialsSelectModalVisible = true;
    },
    zero_retail_price() {
      this.materialItems.forEach((e) => (e.clsl == 0 ? (e.cldj = 0) : {}));
    },
    jgryChange(val) {
      const jgry = val.jgry;
      this.final_jgry = val.jgry;
      this.$off("change", this.jgryChange);
      this.is_jgry_only
        ? this.materialItems.forEach((e) => {
            if (e.id != val.id) {
              this.$set(e, "jgry", jgry);
            }
          })
        : {};
      this.$nextTick(() => {
        this.$on("change", this.jgryChange);
      });
    },
    onSelectMaterial(item) {
      // let index = this.materialItems.findIndex((_item) => _item.id == item.id);
      let index = this.materialItems.length + 1;

      // if (index != -1) {
      //   this.$message.warn("产品已存在");
      //   return;
      // }
      // this.materialItems = this.$functions.insertItem(this.materialItems, {
      this.materialItems.push({
        index: index,
        id: item.id,
        goods: item.goods,
        number: item.goods_number,
        name: item.goods_name,
        guige: item.goods_spec,
        chicun: "",
        huchang: "",
        clsl: 0,
        cldj: this.is_readSalePrice ? item.retail_price : 0,
        clAmount: 0,
        jgsl: 0,
        jgdj: 0,
        jgAmount: 0,
        beizhu: "",
        unit: item.unit_name,
        sales_quantity: 1,
        sales_price: this.is_readSalePrice ? item.retail_price : 0,
        total_quantity: item.total_quantity,
        totalAmount: 1,
        // 大工部分
        cailiao_dg: "",
        chang_dg: 0,
        kuan_dg: 0,
        hou_dg: 0,
        yldj_dg: 0,
        zhong_dg: 0,
        mianji_dg: 0,
        jgcd_dg: 0,
        jgdj_dg: 0,
        jgAmount_dg: 0,
        kongshu_dg: 0,
        kongdj_dg: 0,
        lingjiansl_dg: 0,
        lingjianDj_dg: 0,
        flzhong_dg: 0,
        feiliaodj_dg: 0,
      });

      this.materialItems = [...this.materialItems];
      this.cal_total_quantity();
    },
    removeMaterial(item) {
      let index = this.materialItems.findIndex(
        (_item) => _item.index == item.index
      );
      if (index != -1 && this.materialItems[index].id == item.id) {
        this.materialItems.splice(index, 1);
      }
      // 重新编号，从1开始
      this.materialItems = this.materialItems.map((item, index) => {
        return {
          ...item,
          index: index + 1, // 注意这里我们加了1
        };
      });
    },
    cal_total_zl(item) {
      try {
        // 仅计算加法的表达式解析函数
        const result = this.evaluateAdditionExpression(item.cldz);
        //item.clzl = result;
        this.$set(item, 'clzl', result);
        //console.log("item.clzl:"+item.clzl);
      } catch (error) {
        console.error('输入的表达式有误，请检查输入：', error);
      }
    },
    evaluateAdditionExpression(expression) {
      expression = expression.replace(/\s+/g, '');
      let sum = 0;
      let numStr = '';
      let lastChar = '';
      let i = 0;
      while (i < expression.length) {
        let char = expression.charAt(i);
        if ((char >= '0' && char <= '9') || char === '.') {
          numStr += char;
        } else if (char === '+') {
          if (numStr) {
            sum += parseFloat(numStr);
            numStr = '';
          }
        } else {
          throw new Error('Invalid character in expression');
        }
        lastChar = char;
        i++;
      }
      if (lastChar!== '+' || numStr) {
        sum += parseFloat(numStr);
      }
      sum = parseFloat(sum.toFixed(2));
      //console.log(`最终结果: ${sum}`);
      return sum;
    },
    //根据商品编号计算
    cal_total_quantity() {
      // let arr=_.cloneDeep(this.materialItems)
      let arr = this.materialItems;
      let no_kucun = false
      arr.forEach((item) => {
        let items = arr.filter((i) => i.number == item.number);
        let clsl = 0;
        for (let j = 0; j < items.length; j++) {
          clsl += items[j].clsl;
        }
        item.total_quantity_new = item.total_quantity - clsl;
        if (item.total_quantity_new < 0) {
          this.$message.error(`${item.name} 库存不足`);
          no_kucun=true
        }        
      });
      return no_kucun;
    },
    create() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let ifHasEmptyGoods = false;
          let ifHasEmptyAccounts = false;

          // this.sales_account_items.map((item) => {
          //   if (!item.account || item.collection_amount === "" || item.collection_amount === null) {
          //     ifHasEmptyAccounts = true;
          //   }
          // });
          // if (ifHasEmptyAccounts) {
          //   this.$message.warn("请将结算账户信息填写完整");
          //   return false;
          // }

          if (this.cal_total_quantity()) {
            this.$message.error("添加的商品有库存不足，请更正。");
            return false;
          }
          if (this.materialItems.length == 0) {
            this.$message.warn("未添加产品");
            return false;
          }
          this.materialItems.map((item) => {
            if (item.sales_price === null || !item.sales_quantity) {
              ifHasEmptyGoods = true;
            }
          });
          if (ifHasEmptyGoods) {
            this.$message.warn("销售单价和销售数量必填");
            return false;
          }

          let sales_account_items = [];
          if (
            this.sales_account_item.account &&
            this.sales_account_item.collection_amount > 0
          ) {
            sales_account_items = [this.sales_account_item];
            this.form.account = this.sales_account_item.account;
          }

          this.loading = true;
          let formData = {
            ...this.form,
            // sales_account_items: this.sales_account_items.map((item) => {
            //   delete item.id;
            //   return item;
            // }),
            sales_account_items,
            sales_goods_items: this.materialItems.map((item) => {
              let data_dagong = {
                canshu,
                is_dagong_table: canshu.is_dagong_table,
                yongliaojl: canshu.yongliaojl,
                midu: canshu.midu,
                sunhao: canshu.sunhao,
                cailiao_dg: item.cailiao_dg,
                chang_dg: item.chang_dg,
                kuan_dg: item.kuan_dg,
                hou_dg: item.hou_dg,
                yldj_dg: item.yldj_dg,
                zhong_dg: calzhong_dg(item.chang_dg, item.kuan_dg, item.hou_dg),
                mianji_dg: calmianji_dg(item.chang_dg, item.kuan_dg),
                clAmount_dg: calclAmount(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg
                ),
                jgcd_dg: item.jgcd_dg,
                jgdj_dg: item.jgdj_dg,
                jgAmount_dg: caljgAmount_dg(item.jgcd_dg, item.jgdj_dg),
                kongshu_dg: item.kongshu_dg,
                kongdj_dg: item.kongdj_dg,
                kongAmount_dg: caljgAmount_dg(item.kongshu_dg, item.kongdj_dg),
                lingjiansl_dg: item.lingjiansl_dg,
                lingjianDj_dg: callingjianDj_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg
                ),
                ljtotalAmount_dg: calljtotalAmount_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg,
                  item.lingjiansl_dg
                ),
                flzhong_dg: item.flzhong_dg,
                feiliaodj_dg: item.feiliaodj_dg,
                feiliaoAmount_dg: caljgAmount_dg(
                  item.flzhong_dg,
                  item.feiliaodj_dg
                ),
                shifuAmount_dg: calshifuAmount_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg,
                  item.lingjiansl_dg,
                  item.flzhong_dg,
                  item.feiliaodj_dg
                ),
              };
              const data_dagong_str = JSON.stringify(data_dagong);
              //根据是否为大工表格计算销售出库数量
              let sales_quantity = 0;
              if (canshu.is_dagong_table) {
                sales_quantity = xssl(
                  item.unit,
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.lingjiansl_dg
                );
              } else {
                sales_quantity = item.clsl;
              }
              return {
                goods: item.goods,
                sales_quantity: item.sales_quantity,
                sales_price: item.sales_price,
                sales_quantity,
                guige: item.guige,
                chicun: item.chicun,
                huchang: item.huchang,
                clsl: item.clsl,
                cldj: item.cldj,
                clAmount: item.clAmount,
                jgsl: item.jgsl,
                jgdj: item.jgdj,
                jgAmount: item.jgAmount,
                totalAmount: item.totalAmount,
                data_dagong: data_dagong_str,
                is_dagong_table: canshu.is_dagong_table,
                yongliaojl: canshu.yongliaojl,
                midu: canshu.midu,
                sunhao: canshu.xishu,
                cailiao_dg: item.cailiao_dg,
                chang_dg: item.chang_dg,
                kuan_dg: item.kuan_dg,
                hou_dg: item.hou_dg,
                yldj_dg: item.yldj_dg,
                zhong_dg: calzhong_dg(item.chang_dg, item.kuan_dg, item.hou_dg),
                mianji_dg: calmianji_dg(item.chang_dg, item.kuan_dg),
                clAmount_dg: calclAmount(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg
                ),
                jgcd_dg: item.jgcd_dg,
                jgdj_dg: item.jgdj_dg,
                jgAmount_dg: caljgAmount_dg(item.jgcd_dg, item.jgdj_dg),
                kongshu_dg: item.kongshu_dg,
                kongdj_dg: item.kongdj_dg,
                kongAmount_dg: caljgAmount_dg(item.kongshu_dg, item.kongdj_dg),
                lingjiansl_dg: item.lingjiansl_dg,
                lingjianDj_dg: callingjianDj_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg
                ),
                ljtotalAmount_dg: calljtotalAmount_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg,
                  item.lingjiansl_dg
                ),
                flzhong_dg: item.flzhong_dg,
                feiliaodj_dg: item.feiliaodj_dg,
                feiliaoAmount_dg: caljgAmount_dg(
                  item.flzhong_dg,
                  item.feiliaodj_dg
                ),
                shifuAmount_dg: calshifuAmount_dg(
                  item.chang_dg,
                  item.kuan_dg,
                  item.hou_dg,
                  item.yldj_dg,
                  item.jgcd_dg,
                  item.jgdj_dg,
                  item.kongshu_dg,
                  item.kongdj_dg,
                  item.lingjiansl_dg,
                  item.flzhong_dg,
                  item.feiliaodj_dg
                ),
                beizhu: item.beizhu,
                jgry: item.jgry,
                jgfl: item.jgfl,
              };
            }),
          };
          saleOrderCreate(formData)
            .then((data) => {
              this.$message.success("创建成功");
              this.$router.push({ path: "/sale/sale_record" });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    resetForm() {
      this.form = { other_amount: 0, tableType: false, unitType: false };
      this.sales_account_item = { collection_amount: 0 };
      getSaleOrderNumber().then((data) => {
        this.form = { ...this.form, number: data.number, discount: 100 };
      });
      this.materialItems = [];
      this.handelAddAcount();
    },
  },
  mounted() {
    this.initData();
  },
};
</script>
<style scoped>
::v-deep .ant-table-tbody > tr > td {
  padding: 1px !important;
}
</style>
